package com.noahplat.gateway.filter;

import com.alibaba.fastjson.JSONObject;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * 作者：李景星
 * 描述：token过滤
 * 时间：2020-11-03
 */
@Component
public class AuthFilter implements GlobalFilter {

    //定义常量，token信息封装在http请求header中
    private static final String AUTHORIZE_TOKEN = "Authorization";

    /**
     * 作者：李景星
     * 描述：重写过滤方法
     * 时间：2020-11-03
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取request
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //获取接口路径
        String path = request.getURI().getPath();
        if(URLFilter.hasAuthorization(path)){//判断是否为放行路径，如果为放行路径，直接放行
            return chain.filter(exchange);
        }
        //其他路径做token过滤，token从header中获取
        String authorization = request.getHeaders().getFirst(AUTHORIZE_TOKEN);
        //判断header中是否存在Authorization
        if(StringUtils.isEmpty(authorization)){
            JSONObject message = new JSONObject();
            message.put("flag", true);
            message.put("code", 20007);
            message.put("message", "用户身份未认证");
            byte[] bits = message.toJSONString().getBytes(StandardCharsets.UTF_8);
            DataBuffer buffer = response.bufferFactory().wrap(bits);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //指定编码，否则在浏览器中会中文乱码
            response.getHeaders().add("Content-Type", "text/plain;charset=UTF-8");
            return response.writeWith(Mono.just(buffer));
        }

        return chain.filter(exchange);
    }
}
